import {PAGE_SIZE} from '../constants/common';
import {request} from '../utils/request';
import {action, flow, makeAutoObservable, observable} from 'mobx';
/**
 * home store 全局存储
 */
class ShopStore {
  goodsList: GoodsSimple[] = [];
  page: number = 1;
  refreshing: boolean = false;
  finished: boolean = false; // 数据已经加载完了，没有更多数据
  categoryList: GoodsCategory[] = [];

  constructor() {
    makeAutoObservable(this, {
      goodsList: observable,
      page: observable,
      refreshing: observable,
      finished: observable,
      categoryList: observable,
      resetPage: action,
      requestGoodsList: action,
      requestTop10Category: action,
    });
  }

  resetPage = () => {
    this.page = 1;
  };

  requestGoodsList = flow(function* (
    this: ShopStore, // 方便使用this指针
  ) {
    if (this.refreshing || this.finished) {
      return;
    }
    try {
      this.refreshing = true;
      const params = {
        page: this.page,
        pageSize: PAGE_SIZE,
      };

      const {data} = yield request('goodsList', params);
      if (data?.length) {
        if (this.page === 1) {
          this.goodsList = data;
        } else {
          this.goodsList = [...this.goodsList, ...data];
        }
        this.page = this.page + 1;
      } else {
        if (this.page === 1) {
          this.goodsList = [];
        } else {
          //已经加载完了
        }
        this.finished = true;
      }
    } catch (error) {
      console.log(error);
    } finally {
      this.refreshing = false;
    }
  });

  requestTop10Category = flow(function* (this: ShopStore) {
    try {
      const {data} = yield request('top10Category', {});
      this.categoryList = data || [];
    } catch (error) {
      console.log(error);
    }
  });
}

/**
 * ESM单例导出
 */
export default new ShopStore();
